<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
            ref="dateRangePicker"
            v-model:value="vdata.searchData['queryDateRange']"
            customDateRangeType="dateTime"
          />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.receiverId" placeholder="分账接受者ID" />
        <jeepay-text-up v-model:value="vdata.searchData.receiverGroupId" placeholder="分账账号组ID" />
        <jeepay-text-up v-model:value="vdata.searchData.appId" placeholder="应用AppId" />
        <jeepay-text-up v-model:value="vdata.searchData.payOrderId" placeholder="支付订单号" />
        <jeepay-text-up v-model:value="vdata.searchData.accNo" placeholder="分账接收账号" />

        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.state" placeholder="分账状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">待分账</a-select-option>
            <a-select-option value="1">分账成功</a-select-option>
            <a-select-option value="2">分账失败</a-select-option>
            <a-select-option value="3">分账处理中</a-select-option>
            <a-select-option value="4">分账已受理</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        :rowSelection="{ type: 'checkbox', selectedRowKeys: vdata.recordIdList, onChange: infoTableSelectChangeFunc }"
        rowKey="recordId"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_DIVISION_RECORD_RESEND')" type="primary" @click="resendBatchFunc"><redo-outlined />批量重新发起分账</a-button>
        </template>
        <template #bodyCell="{column,record}">
          <template v-if="column.key == 'calDivisionAmount'"><b>￥{{ record.calDivisionAmount/100 }}</b></template>
          <template v-if="column.key == 'divisionRefundAmount'"><b>￥{{ record.refundAmount/100 }}</b></template>
          <template v-if="column.key == 'calRealAmount'"><b>￥{{ (record.calDivisionAmount - record.refundAmount)/100 }}</b></template>
          <template v-if="column.key == 'payOrderAmount'">￥{{ record.payOrderAmount/100 }}</template>
          <template v-if="column.key == 'state'">
            <a-tag v-if="record.state == 0" color="blue">待分账</a-tag>
            <a-tag v-if="record.state == 1" color="green">分账成功</a-tag>
            <a-tag v-if="record.state == 2" color="volcano">分账失败</a-tag>
            <a-tag v-if="record.state == 3" color="orange">分账处理中</a-tag>
            <a-tag v-if="record.state == 4" color="orange">分账已受理</a-tag>
          </template>
          
          <template v-if="column.key == 'ifCode'">
            <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
              <label v-if="record.ifCode == item.ifCode">{{ item.ifName }}({{ item.ifCode }})</label>
            </template>
          </template>
          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->
            <a-button v-if="record.state == 2 && $access('ENT_DIVISION_RECORD_RESEND')" type="link" @click="redivFunc(record.recordId)">重试</a-button>
            <a-button v-if="$access('ENT_DIVISION_RECORD_VIEW')" type="link" @click="detailFunc(record.recordId)">详情</a-button>
          </template>
          <template v-if="column.key == 'payOrderDivisionAmount'">{{ (record.payOrderDivisionAmount / 100).toFixed(2) }}</template>
          <template v-if="column.key == 'divisionProfit'">{{ (record.divisionProfit * 100).toFixed(2) }}%</template>
        </template>
      </JeepayTable>
    </a-card>

    <Detail ref="recordDetail" />

    <ResendModal ref="resendModalRef" />
  </page-header-wrapper>
</template>
<script lang="ts" setup>
import { API_URL_PAY_ORDER_DIVISION_RECORD_LIST, API_URL_IFDEFINES_LIST, req } from '@/api/manage'
import moment from 'moment'
import Detail from './Detail.vue'
import ResendModal from './ResendModal.vue'
import { reactive, ref,getCurrentInstance, provide, onMounted } from 'vue'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
// eslint-disable-next-line no-unused-vars

const tableColumns = reactive([
  { key: 'calDivisionAmount', title: '分账金额（首次）' },
  { key: 'divisionRefundAmount', title: '回退金额' },
  { key: 'calRealAmount', title: '实际入账金额' },
  { key: 'batchOrderId', title: '分账批次号', dataIndex: 'batchOrderId' },
  { key: 'payOrderId', title: '支付订单号', dataIndex: 'payOrderId' },
  { key: 'ifCode', title: '支付接口' },
  { key: 'payOrderAmount', title: '订单金额' },
  { key: 'payOrderDivisionAmount', dataIndex: 'payOrderDivisionAmount', title: '分账基数'  },
  { key: 'receiverAlias', title: '账号别名', dataIndex: 'receiverAlias' },
  { key: 'accNo', title: '接收账号', dataIndex: 'accNo' },
  { key: 'accName', title: '账号姓名', dataIndex: 'accName' },
  { key: 'relationTypeName', title: '分账关系类型', dataIndex: 'relationTypeName' },
  { key: 'divisionProfit', dataIndex: 'divisionProfit', title: '分账比例'},
  { key: 'state', title: '分账状态', scopedSlots: { customRender: 'stateSlot' } },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期' },
  { key: 'op', title: '操作',   fixed: 'right', align: 'center' }
])

  const recordDetail = ref()
  const resendModalRef = ref()
  const infoTable = ref()
  const dateRangePicker = ref()
  const vdata : any = reactive({
    btnLoading: false,
    tableColumns: tableColumns,
    searchData: { queryDateRange: 'today' } as any,
    createdStart: '', // 选择开始时间
    createdEnd: '', // 选择结束时间
    visible:false,
    recordIdList: [] as any, // 多选ID集合
    ifCodeList: [],
  })

    // 注入搜索函数
  provide('searchFunc', searchFunc)

  
  onMounted(() => {
    req.list(API_URL_IFDEFINES_LIST, {state:1}).then((res) => {
        vdata.ifCodeList = res
    })
  })

  function resetFunc() {
    dateRangePicker.value.returnSelectModel()
    vdata.searchData = { queryDateRange: 'today' }
  }

  // 请求table接口数据
  function reqTableDataFunc(params){
    return req.list(API_URL_PAY_ORDER_DIVISION_RECORD_LIST, params)
  }

  function searchFunc() { // 点击【查询】按钮点击事件
    infoTable.value.refTable(true)
  }

  function detailFunc (recordId) {
    recordDetail.value.show(recordId)
  }

  function onChange (date, dateString) {
    vdata.searchData.createdStart = dateString[0] // 开始时间
    vdata.searchData.createdEnd = dateString[1] // 结束时间
  }

  function disabledDate (current) { // 今日之后日期不可选
    return current && current > moment().endOf('day')
  }

  function onClose () {
    vdata.visible = false
  }

// 表格多选
function infoTableSelectChangeFunc(selectedRowKeys, selectedRows) {
  vdata.recordIdList = selectedRowKeys
  if (selectedRows && selectedRows.length > 0) {
    selectedRows.forEach(e => {
      if (e.state != 2) {
        $infoBox.message.warn('重新发起分账只针对分账失败的订单有效，建议通过筛选条件缩小范围，再批量重试分账')
        throw new Error('包含非分账失败状态的')
      }
    })
  }
}

// 重新发起分账
function redivFunc(recordId) {
  resendModalRef.value.show([recordId])
}

// 批量重试分账
function resendBatchFunc() {
  if (vdata.recordIdList.length <= 0) {
    $infoBox.message.error('请选择分账记录')
    return
  }

  resendModalRef.value.show(vdata.recordIdList)
}

</script>
